package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class TraverseFilesystemsWithSimpleFileVisitor {
	public static void main(String[] args) {
		try {
			Path path = Paths.get("E:/Copy");
			ListFiles listFiles = new ListFiles();
			Files.walkFileTree(path, listFiles);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}

class ListFiles extends SimpleFileVisitor<Path> {
	private final int indentionAmount = 3;
	private int indentionLevel;

	ListFiles() {
		indentionLevel = 0;
	}

	private void indent() {
		for (int i = 0; i < indentionLevel; i++) {
			System.out.print(' ');
		}
	}

	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
		indent();
		System.out.println("访问文件:" + file.getFileName());
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult postVisitDirectory(Path directory, IOException e) {
		indentionLevel -= indentionAmount;
		indent();
		System.out.println("文件夹结束遍历: " + directory.getFileName());
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) {
		indent();
		System.out.println("即将遍历目录: " + directory.getFileName());
		indentionLevel += indentionAmount;
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFileFailed(Path file, IOException exc)
			throws IOException {
		System.out.println("发生文件遍历错误");
		return super.visitFileFailed(file, exc);
	}
}
